import { HttpException, HttpStatus } from '@nestjs/common'
import { getMetadataArgsStorage } from 'typeorm'
import { UserFromRequest } from 'types/global'
import { HttpExceptionEnum } from 'types/http-exception'

/**
 * @description 生成select语句
 * @param entity 实体
 * @param entityName 实体名称（可选）
 */
const generateSelect = (entity: any, entityName?: string) => {
  // 如果没有提供 entityName，则使用 entity 的名称并转换为小写
  if (!entityName) {
    entityName = entity.name.toLowerCase()
  }

  // 获取实体的元数据
  const metadataArgsStorage = getMetadataArgsStorage()

  // 获取实体的列信息
  const columns = metadataArgsStorage.columns.filter(
    (column) => column.target === entity
  )

  let select = columns.map((column) => {
    return `${entityName}.${column.propertyName} as ${column.propertyName}`
  })

  select = select.concat([
    'createdBy.id as createdById',
    'createdBy.name as createdByName',
    'updatedBy.id as updatedById',
    'updatedBy.name as updatedByName'
  ])
  return select
}

/**
 * @description 判断当前角色是否有权限进行操作
 * @param user 角色编码
 * @param createBy 操作编码
 */
const hasPermission = (user: UserFromRequest, createBy: number) => {
  if (user.roleCode === 'Administrator') return true
  if (user.userId !== createBy)
    throw new HttpException(
      HttpExceptionEnum.USER_NOT_PERMISSION,
      HttpStatus.FORBIDDEN
    )
}

export { generateSelect, hasPermission }
